from cache_base import *
from cache_entity import *
from common import *
from memory_file import TransactionBase, MemoryFileOpt
import random
import time
from multiprocessing import Process
keys_list = list()
keys_value_list = list()
cache_base = CacheBase(table_name="test")


def add_commit():
    # cb = CacheBase(table_name="test")
    max_time = 0
    count_aa = 0
    t = time.time()
    count = 0
    for ks in keys_list:
        t_max = time.time()
        count += 1
        cache_base.add(keys=ks, data=keys_value_list[count_aa])
        # print("add num: %d" % count)
        t_max = time.time() - t_max
        max_time = t_max if t_max > max_time else max_time
        # print("now add: %d" % count_aa)
        count_aa += 1
    print("======================================")
    print("max add time: %f" % max_time)
    # MemoryFileOpt.commit()
    time.sleep(1)
    stat.print()
    print("======================================")


def create_test():
    data_count = 50
    for i in range(0, data_count):
        keys = FieldEntity()
        keys.add("abe", "你好%d" % random.randint(0, data_count))
        keys.add("abd", "大家%d" % random.randint(0, data_count))
        keys.add("aaa", "测试%d" % random.randint(0, data_count))
        str_v = ""
        for fi in keys.field_list:
            str_v = "%s%s:" % (str_v, fi.base_value)
        print(str_v)
        keys_value_list.append(bytes(str_v, "utf-8"))
        keys_list.append(keys)
    print("data count :%d;" % len(keys_list))
    time.sleep(1)


def callback(data):
    print("callback")


def find_test():
    # cache_base = CacheBase(table_name="test")
    keys1 = ConditionCollect()
    keys1.add("aaa", "测试%d" % 30, SymbolEnum.gt)
    keys1.add("abd", "大家%d" % 20, SymbolEnum.lt)
    # keys1.add("abd", "大家%d" % 3)
    t2 = time.time()
    v = cache_base.find(keys1)
    print("find: %d; find time: %f; " % (v.get_count(), time.time() - t2))
    time.sleep(1)
    while v.has_next():
        print(str(v.next().get_data(), "utf-8"))
    time.sleep(1)


if __name__ == "__main__":
    read = True
    create_test()
    add_commit()
    # TransactionBase(add_commit)
    find_test()
    MemoryFileOpt.close()

